/**
 * Created by muluolanke on 2017/2/17.
 */
function getCIGCookie(c_name,subname)
{
    if (document.cookie.length>0)
    {
        c_start=document.cookie.indexOf(c_name + "=")
        //console.log(c_start);
        if (c_start!=-1)
        {
            c_start=c_start + c_name.length+1
            c_end=document.cookie.indexOf(";",c_start)
            if (c_end==-1) c_end=document.cookie.length
            mycookielist = unescape(document.cookie.substring(c_start,c_end));
            mycookiearr =mycookielist.split("|");
            //console.log(mycookiearr.length);
            for (i=0;i<mycookiearr.length;i++){
                subarr =mycookiearr[i].split(":");
                if(subarr[0]==subname)
                {
                    return subarr[1];
                }
            }
            return ""
        }
    }
    return ""
}
//$(function(){
$(document).ready(function(){
    /*$("a").click(function(){
        $("a").attr("data-href",$(this).attr("href"));
        $("a").removeAttr("href");
        setTimeout(function(){
            location.href=$(this).attr("data-href");
        },500)
    })*/

    /*$("p a.returnews").attr("href","javascript:;");*/
    // 设置媒体来路
   /* if ($.query.get('utm_source') != undefined) {
        $.cookie('utm_source', $.query.get('utm_source'));
    }
    if ($.query.get('utm_medium') != undefined) {
        $.cookie('utm_medium', $.query.get('utm_medium'));
    }
    if ($.query.get('utm_campaign') != undefined) {
        $.cookie('utm_campaign', $.query.get('utm_campaign'));
    }
    if ($.query.get('utm_content') != undefined) {
        $.cookie('utm_content', $.query.get('utm_content'));
    }*/

    //if($(".index-banner").length<=0){
    //     $("a").each(function(){
    //         if(!$(this).hasClass("banner_img")){
    //             var href=$(this).attr("href");
    //             $(this).removeAttr("href");
    //             $(this).attr("data-href",href)
    //         }
    //     })
    //     $("a").click(function(){
    //         console.log("000");
    //         var href=$(this).attr("data-href");
    //         var text=$(this).attr("title");
    //         var id=$(this).attr("title-id");
    //         if($(".news-list").length>0 && $(".index-banner").length>0 &&$(this).closest(".text-list").length>0){
    //             ga('send', 'event', 'PC14_CX-4产品站', '首页', 'PC14_首页_新闻资讯_'+id+'_'+text+'-点击');
    //         }else if($(".news-list").length>0 && $(".index-banner").length<=0){
    //             ga('send', 'event', 'PC14_CX-4产品站', '最新资讯', 'PC14_最新资讯_新闻资讯_'+id+'_'+text+'-点击');
    //         }else if($(".newslist").length>0){
    //             ga('send', 'event', 'PC14_CX-4产品站', '最新资讯', 'PC14_最新资讯_新闻资讯_'+id+'_'+text+'-点击');
    //         }else if($(".officecontent").length>0){
    //             ga('send', 'event', 'PC14_CX-4产品站', '最新资讯', 'PC14_最新资讯_热门活动_'+id+'_'+text+'-点击');
    //         }
    //         setTimeout(function(){
    //             window.location.href=href;
    //         },300)
    //     })
    //}
    $(".menu-test").click(function(){
        $(".test-div").fadeIn();
    });
    $(".close").click(function(){
        $(".test-div").fadeOut();
    });
    $(".test-div").find(".sex span").removeClass("current");
    $(".test-div").find("input[name='sex']").val("");
    jQuery('[placeholder]').focus(function() {
        var input = jQuery(this);
        if (input.val() == input.attr('placeholder')) {
            input.val('');
            input.removeClass('placeholder');
        }
    }).blur(function() {
        var input = jQuery(this);
        if (input.val() == '' || input.val() == input.attr('placeholder')) {
            input.addClass('placeholder');
            input.val(input.attr('placeholder'));
        }
    }).blur().parents('form').submit(function() {
        jQuery(this).find('[placeholder]').each(function() {
            var input = jQuery(this);
            if (input.val() == input.attr('placeholder')) {
                input.val('');
            }
        })
    });

    $("body").on('click', ".sex span", function(event){
        var $this = $(event.target);
        var $form = $this.closest("form");
        var data_sex=$this.attr("data-sex");
        $this.parent().children().removeClass("current");
        $this.addClass("current");
        $form.find("input[name='sex']").val(data_sex);

    });
    testDriving();


});

//预约试驾初始化
function testDriving(){
    var cityName,proName,deaName;
    var  $prov =$("select[name='dealer_province']")
    //,$dealerquery_province = $('#dealer_province')
        ,$city = $("select[name='dealer_city']")
    // ,$dealerquery_city = $('#dealer_city')
        ,$dealer = $("select[name='dealer']")
        ,$prod
        ,$pattern = $("select[name='product']")
        ,$name = $("input[name='name']")
        ,$sex=$("input[name='sex']")
        ,$mobile =$("input[name='mobile']");
    var $product = 0,$way=34;
    $.ajax({
        url: '//dmp.faw-mazda.com/api/Gather/get_province_list?identity=379CB826-C594-093F-0753-4724AAC62977',
        dataType: 'jsonp',
        jsonp: "jsoncallback",
        success: function(msg) {
            var province = "<option value=''>请选择省份</option>";
            $(msg.data).each(function(i, item) {
                province += "<option value=" + item.id + ">" + item.name + "</option>";
                // $prov.append('<option value="' + item.id + '">' + item.name + '</option>');
            });
            $prov.html(province);

        }
    });

    var dataList = new Array();

    $("body").on('change', "select[name='dealer_province']",function(event){
        var $prov = $(event.target);
        var $form = $prov.closest("form");
        var $city = $form.find("select[name='dealer_city']");
        var $dealer = $form.find("select[name='dealer']");
        var pro = $prov.val();
        proName=pro;
        $.ajax({
            // url: 'http://log.faw-mazda.dma.cig.com.cn/lms_api/gather/get_city_list?p_id='+$("#province").val(),
            url: '//dmp.faw-mazda.com/api/Gather/get_city_list?p_id='+pro+'&customer_id=81&identity=379CB826-C594-093F-0753-4724AAC62977&is_dealer=',
            // url: 'https://dmp.faw-mazda.com/api/Gather/get_city_list?p_id=&identity=379CB826-C594-093F-0753-4724AAC62977&is_dealer=',
            dataType: 'jsonp',
            jsonp: "jsoncallback",
            success: function(msg) {
                console.log(msg);
                var city = "<option value=''>请选择城市</option>";
                $(msg.data).each(function(i, item) {
                    city += "<option value=" + item.id + ">" + item.name + "</option>";
                });
                $city.html(city);

            }
        })
    })

    $("body").on('change', "select[name='dealer_city']", function(event){
        var $city = $(event.target);
        var $form = $city.closest("form");
        var $prov = $form.find("select[name='dealer_province']");
        var $dealer = $form.find("select[name='dealer']");
        var city = $city.val();
        cityName=city;
        $.ajax({
            // url: 'http://log.faw-mazda.dma.cig.com.cn/lms_api/gather/get_dealer_list?cityid='+$("#city").val(),
            url: '//dmp.faw-mazda.com/api/Gather/get_dealer_list?customer_id=81&identity=379CB826-C594-093F-0753-4724AAC62977&provinceid='+proName+'&cityid='+cityName+'&districtid=&dea_area1=&dea_area2=',
            dataType: 'jsonp',
            jsonp: "jsoncallback",
            success: function(msg) {
                var jx = "<option value=''>请选择</option>";
                $(msg.data).each(function(i, item) {
                    jx += "<option value=" + item.dea_id + ">" + item.dea_name + "</option>";
                });
                $dealer.html(jx);
            }
        })
    })

    $("body").on('click', ".submit",function(event){
        event.preventDefault();
        // ga('send', 'event', 'C05_CX-4产品站PC_预约试驾', '预约试驾', 'C05_CX-4产品站PC_预约试驾提交');
        var $this = $(event.target);
        var $form = $this.closest("form");
        var $pattern = $form.find("select[name='product']")
            ,$name =  $form.find("input[name='name']")
            ,$sex= $form.find("input[name='sex']")
            ,$mobile = $form.find("input[name='mobile']");
        var $prov = $form.find("select[name='dealer_province']");
        var $city = $form.find("select[name='dealer_city']");
        var $dealer = $form.find("select[name='dealer']");

        var provincetext=$prov.find("option:selected").text();
        var citytext=$city.find("option:selected").text();
        var jxtext=$dealer.find("option:selected").text();
        var sextext=$(".sex").find("span.current").text();

        var utm_source = getCIGCookie('dcad7','utm_source');//$.cookie('utm_source') || ''; //广告来源
        var utm_content = getCIGCookie('dcad7','utm_content');//$.cookie('utm_content') || ''; //广告内容
        var utm_medium = getCIGCookie('dcad7','utm_medium');//$.cookie('utm_medium') || ''; //广告媒介
        var utm_campaign = getCIGCookie('dcad7','utm_campaign');//$.cookie('utm_campaign') || ''; //广告活动
        /*
         var activity ='10018';
         if(utm_campaign=='9800933')
         {
         activity ='10028';
         }
         else if(utm_campaign=='9717973' || utm_campaign=='9719233'|| utm_campaign=='9722298')
         {
         activity ='10018';
         }
         else{activity ='';}
         */
        var activity ='';
         if(utm_campaign=='11019643')
         {
         activity ='10100';
         }
        //var myDate=new Date();
        //http://log.faw-mazda.dma.cig.com.cn/lms_api/gather/index?dcad=utm_source:baidu|utm_content:shouye|utm_medium:shouyetonglan|utm_campaign:test&dcev=customer:2|product:1|pattern:2|name:test|sex:1|mobile:13686868866|dealer_province:2|dealer_city:12|dealer_area:12|dealer:13|ctype:98|way:29|channel:59|email:test@test.com|activity:|remarks:test|media:baidu&dcu=cbe-17049
        //http://log.faw-mazda.dma.cig.com.cn/lms_api/gather/index?dcad=utm_campaign%3A9320996|utm_source%3AAutoSmart|utm_content%3AAUTO_DSP|utm_medium%3ATengXunZiYuanJuZhenTuWenGuangGaobannerWenZiLianBanPingDengSanDaJiaoYiShiChangZiYuan1|WT.mc_id%3A127000723&dcev=product%3A1413|name%3Adfgdfg|sex%3A0|mobile%3A13333333333|dealer_province%3A25|dealer_city%3A120000|dealer%3A10395|email%3A|buycartime%3A%E4%B8%89%E5%91%A8%E5%86%85%7Cway%3A29|channel%3A65|activity%3A10001|ctype%3A98|customer%3A2|remarks%3A%E9%A2%84%E7%BA%A6%E8%AF%95%E9%A9%BE&_=1451896066159

        //检查

        if($name.val() == ""){
            alert("请输入您的姓名!");
            $name.focus();
            return false;
        }
        if($mobile.val() == ""){
            alert("请输入您的手机号码!");
            $mobile.focus();
            return false;
        }
        if(!isMobile($mobile.val())){
            alert("请正确输入您的手机号码!");
            $mobile.focus();
            return false;
        }
        if($prov.val() == ""){
            alert("请选择所在省份!");
            $prov.focus();
            return false;
        }
        /*if($city.val() == ""){
         alert("请选择所在城市!");
         $city.focus();
         return false;
         }*/
        if($dealer.val() == ""){
            alert("请选择经销商!");
            $dealer.focus();
            return false;
        }
        if($pattern.val() == ""){
            alert("请选择车型!");
            $pattern.focus();
            return false;
        }
       // var dcad = 'utm_source:' + ($.cookie('utm_source') || '') + ',utm_content:' + ($.cookie('utm_content') || '') + ',utm_medium:' + ($.cookie('utm_medium') || '') + ',utm_campaign:' + ($.cookie('utm_campaign') || '') + '';

        var dcad = "utm_source:" + utm_source + ",utm_content:" + utm_content + ",utm_medium:" + utm_medium + ",utm_campaign:" + utm_campaign;
        var formdata = {
            product         : '20008',
            pattern         :$pattern.val().toString(),
            name            : $name.val().toString(),
            sex             : $sex.val().toString(),
            mobile          : $mobile.val().toString(),
            dealer_province : $prov.val().toString(),
            dealer_city     :$city.val().toString(),
            dealer          : $dealer.val().toString(),
            email           : '',
            buycartime      : '',
            way             : '29',
            channel         : '60',
            create_time     :(Date.parse(new Date())/1000),
            activity        :activity,
            ctype           : '98',
            customer        :  '81',
            remarks         : '预约试驾'
        };
        var dcev = "";
        var jsondata ='{"customer": "81","product":"20008","activity":"10100","name":"'+ $name.val().toString()+'","sex":"'+ $sex.val().toString()+'", "mobile": "'+$mobile.val().toString()+'","dealer":"'+ $dealer.val().toString()+'","way": "29","ctype": "98","channel": "60","create_time":"'+ (Date.parse(new Date())/1000)+'","media":"'+getCIGCookie('dcad7','utm_source')+'","utm_medium" : "'+getCIGCookie('dcad7','utm_medium')+'","utm_content" :"'+ getCIGCookie('dcad7','utm_content')+'","utm_source" :"'+getCIGCookie('dcad7','utm_source')+'","utm_campaign" :"'+getCIGCookie('dcad7','utm_campaign')+'"}';
        //var jsondata = '{"customer": "81","product":"20008","name":"'+ username+'","sex":"1", "mobile": "'+mobile+'","dealer":"'+dealerid+'","way": "29","ctype": "'+(ordertype=='试驾'?"98":"97")+'","channel": "64","create_time":"'+ (Date.parse(new Date())/1000)+'","media":"'+getCIGCookie('CIGDCAD','utm_source')+'","utm_medium" : "'+getCIGCookie('CIGDCAD','utm_medium')+'","utm_content" :"'+ getCIGCookie('CIGDCAD','utm_content')+'","utm_source" :"'+getCIGCookie('CIGDCAD','utm_source')+'","utm_campaign" :"'+getCIGCookie('CIGDCAD','utm_campaign')+'"}';
        for (var f in formdata) {
            dcev += f + ":" + formdata[f] + ",";
        }
        dcev = dcev.substring(0, dcev.length - 1);

        var data = {
            identity: '379CB826-C594-093F-0753-4724AAC62977',
            dcad: dcad,
            dcev: dcev
        };
        var dmadata = {
            identity: '379CB826-C594-093F-0753-4724AAC62977',
            json: jsondata
        }


        $.ajax({
            url: '//dma.cig.com.cn/api/lms_clue_api/index',
            dataType: "jsonp",
            jsonp: "jsoncallback",
            data: dmadata,
            success: function(msg) {
                console.log(msg);
                if (msg.code == 200) {
                    //ga('send', 'event', 'PC14_CX-4产品站', '首页', 'PC14_首页_预约试驾-提交成功,{'dimension1':+ '_' ++ '_'  +  + '_' +  + '_'+ '_'});
                    //ga('send', 'event', 'PC14_CX-4产品站', '首页', 'PC14_首页_预约试驾-提交成功',{'dimension1': $name.val().toString()+'_'+$mobile.val().substring(3,11)+ '_' +provincetext+'_'+citytext+'_'+jxtext+'_'+sextext+'_'+$pattern.val()});
                    console.log($name.val().toString()+'_'+$mobile.val().substring(3,11)+ '_' +provincetext+'_'+citytext+'_'+jxtext+'_'+sextext+'_'+$pattern.val());
                    alert("提交成功");
                    $("select[name='dealer_province']").val('');
                    $("select[name='dealer_city']").val('');
                    $("select[name='dealer']").val('');
                    $("select[name='product']").val('');
                    $("input[name='name']").val('');
                    $("input[name='mobile']").val('');
                    $("input[name='sex']").val("");
                    $(".sex span").removeClass("current");

                } else {
                    alert("提交失败，请稍后再试");
                }
            }
        })


        /* var dcev = "";
         for (var f in formdata) {
         dcev += f + ":" + formdata[f] + "|";
         }
         dcev = dcev.substring(0, dcev.length - 1);

         var data = {
         dcad: dcad,
         dcev: dcev
         };

         $.ajax({
         url: 'https://dmp.faw-mazda.com/api/lms_clue_api/index?identity=379CB826-C594-093F-0753-4724AAC62977&json=',
         dataType: "jsonp",
         jsonp: "jsoncallback",
         data: data,
         success: function(msg) {
         console.log(msg);
         if (msg.code == 200) {
         //ga('send', 'pageview', '/VP/CX-4产品站PC/预约试驾成功',{'dimension1': cartype+'_'+provincetext+ '_' +citytext+'_'+jxtext+'_'+username+'_'+sex+'_'+tel.substring(3,11)});
         alert("提交成功");
         $("select[name='dealer_province']").val('');
         $("select[name='dealer_city']").val('');
         $("select[name='dealer']").val('');
         $("select[name='product']").val('');
         $("input[name='name']").val('');
         $("input[name='mobile']").val('');
         } else {
         alert("提交失败，请稍后再试");
         }
         }
         })*/
    })
}

function isMobile(str){
    var patrn=/^(1[0-9])\d{9}$/;
    if (!patrn.exec(str)) return false
    return true
}
